<template>
	<view class="w-full">
		<nut-tabs
			v-model="activeTab"
			color="#ffe243"
			background="#fff"
			size="large"
		>
			<nut-tab-pane
				title="按油相重量(g)"
				pane-key="1"
				style="padding: 0; background-color: transparent"
			>
			</nut-tab-pane>
			<nut-tab-pane
				title="按油相比例(%)"
				pane-key="2"
				style="padding: 0; background-color: transparent"
			>
			</nut-tab-pane>
		</nut-tabs>
		<!-- tab内容 -->
		<view class="w-full h-full bg-[f7f8fa]">
			<view>
				<view class="easy_between align-middle mt-3 mb-3 pl-4 pr-4">
					<text class="h_m_gray">油相</text>
					<view @tap="openChooseOil"
						><image
							class="w-[6vw] h-[6vw]"
							src="../../assets/plus.svg"
					/></view>
				</view>
				<view v-if="activeTab == 2"
					><view
						class="w-full h-[15vw] easy_between mb-0.5 pl-4 pr-4"
						style="background-color: #fff"
					>
						<view style="width: 99vw" class="easy_start">
							<view>油相总重</view>
							<view class="text-xs ml-3 text-[#6066ea]"
								>剩余:{{ restProportion }}%</view
							>
						</view>
						<nut-input
							v-model="formData.totalOilWeight"
							type="digit"
							placeholder="请输入"
							input-align="right"
							:border="false"
						/><text>克</text>
					</view>
				</view>
				<view v-for="(item, index) in oilLists" :key="index"
					><view
						class="w-full h-[15vw] easy_between mb-0.5 pl-4 pr-4"
						style="background-color: #fff"
					>
						<view @tap="deleteOil(index)">
							<image
								class="w-[5vw] h-[5vw] mr-5"
								src="../../assets/delete.svg"
						/></view>
						<view style="width: 60vw"
							><view class="easy_between w-full"
								><view class="ellipsis">{{ item.name }}</view>
								<!-- 按比例计算的重量 -->
								<view
									v-if="activeTab == 2"
									class="text-xs ml-3 text-[#6066ea]"
									>{{ computedWeight(item) || 0 }}g</view
								></view
							><view class="easy_between"
								><view class="text-xs mt-1 mr-1"
									>皂化价：{{ item.zhj }}</view
								>
								<!-- 编辑脂肪酸的功能暂时放放 -->
								<!-- <view @tap="openEditOil(item, index)"
											><image
												class="w-[5vw] h-[5vw] mr-5"
												src="../../assets/edit.svg"
										/></view>  -->
							</view></view
						>
						<!-- 重量 -->
						<nut-input
							v-if="activeTab == 1"
							v-model="item.weight"
							type="digit"
							placeholder="请输入"
							input-align="right"
							:border="false"
							@blur="formatNumber(item, 'weight')"
						/>
						<!-- 比例 -->
						<nut-input
							v-else
							max-length="5"
							v-model="item.proportion"
							type="digit"
							placeholder="请输入"
							input-align="right"
							:border="false"
							@blur="formatNumber(item, 'proportion')"
						/>
						<text class="ml-4">{{ activeTab == 1 ? '克' : '%' }}</text>
					</view>
				</view>
			</view>
			<!-- 基本参数 -->
			<view>
				<view class="easy_between align-middle mt-3 mb-3 pl-4 pr-4">
					<text class="h_m_gray">基本参数</text>
				</view>

				<view
					><view
						class="w-full h-[15vw] easy_between mb-0.5 pl-4 pr-4"
						style="background-color: #fff"
					>
						<view style="width: 50vw">碱(KOH)纯度</view>
						<nut-input
							v-model="formData.NaOHPurity"
							type="digit"
							placeholder="KOH纯度"
							input-align="center"
							:border="false"
							@blur="formatNumber(formData, 'NaOHPurity')"
						/><text>%</text>
					</view>
					<view
						class="w-full h-[15vw] easy_between mb-0.5 pl-4 pr-4"
						style="background-color: #fff"
					>
						<view style="width: 50vw">水相</view>
						<nut-input
							v-model="formData.water"
							type="digit"
							placeholder="碱的倍数"
							input-align="center"
							:border="false"
							@blur="formatNumber(formData, 'water')"
						/><text>倍</text>
					</view>
					<view
						class="w-full h-[15vw] easy_between mb-0.5 pl-4 pr-4"
						style="background-color: #fff"
					>
						<view style="width: 50vw">减碱</view>
						<nut-input
							v-model="formData.substractNaOH"
							type="digit"
							placeholder="请输入"
							input-align="center"
							:border="false"
							@blur="formatNumber(formData, 'substractNaOH')"
						/><text>%</text>
					</view>
				</view>
			</view>

			<!-- 超脂/添加物 -->
			<view>
				<view class="easy_between align-middle mt-3 mb-3 pl-4 pr-4">
					<text class="h_m_gray">超脂/添加物</text>
					<view @tap="addOther"
						><image
							class="w-[6vw] h-[6vw]"
							src="../../assets/plus.svg"
					/></view>
				</view>
				<view v-for="(item, index) in otherLists" :key="item.id"
					><view
						class="w-full h-[15vw] easy_between mb-0.5 pl-4 pr-4"
						style="background-color: #fff"
					>
						<view @tap="deleteOther(index)"
							><image
								class="w-[5vw] h-[5vw] "
								src="../../assets/delete.svg"
						/></view>
						<view style="width: 200vw">
							<nut-input
								v-model="item.name"
								placeholder="添加物名称"
								input-align="left"
								:border="false"
								max-length="20"
							/>
						</view>
						<nut-input
							v-model="item.weight"
							type="digit"
							placeholder="请输入"
							input-align="right"
							:border="false"
							@blur="formatNumber(item, 'weight')"
						/><text  class="ml-4">克</text>
					</view>
				</view>
			</view>
			<!-- 备注 -->
			<view style="margin-bottom: 16rpx">
				<view class="easy_between align-middle mt-3 mb-3 pl-4 pr-4">
					<text class="h_m_gray">备注</text>
				</view>
				<view>
					<nut-textarea
						v-model="formData.remark"
						max-length="500"
						limit-show
						placeholder="请输入"
				/></view>
			</view>
			<!-- 占位 -->
			<view class="h-[130rpx]"></view>
		</view>
		<!-- ---- -->
	</view>
	<!-- 按钮 -->
	<view
		style="
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 130rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			background-color: #fff;
			padding: 3vw 4vw;
			z-index: 999;
		"
	>
		<view
			class="h-full w-[49%] easy_center bg-[#f7f8fa] mr-[2vw] rounded-md"
			@tap="clearData"
			>清空</view
		><view
			class="h-full w-[49%] easy_center bg-[#6066ea] text-[#fff] rounded-md"
			@tap="handleCompute"
			>计算</view
		>
	</view>
</template>

<script lang="ts" setup>
import BigNumber from 'bignumber.js';
import Taro, { eventCenter, useLoad, useUnload } from '@tarojs/taro';
import { ref, reactive, computed } from 'vue';

const initialFormData = {
	totalOilWeight: 500,
	NaOHPurity: 90,
	water: 3,
	substractNaOH: 0,
	remark: '',
};
const formData = reactive(initialFormData);
const activeTab = ref(1);

// 按比例计算重量
const computedWeight = (item: any) => {
	const w = new BigNumber(formData.totalOilWeight || 0)
		.multipliedBy(item.proportion || 0)
		.dividedBy(100);
	item.weight = w.toFixed(2);
	return w.toFixed(2);
};

const openChooseOil = () => {
	Taro.navigateTo({
		url: '/packageOil/pages/oilList/index',
	});
};

const openEditOil = (item: any, index: number) => {
	Taro.navigateTo({
		url: '/pages/editOilInfo/index',
	});
};

const restProportion = computed(() => {
	const totalProportion = oilLists.value.reduce(
		(pre: BigNumber, cur: any) => pre.plus(cur.proportion || 0),
		new BigNumber(0)
	);
	return new BigNumber(100).minus(totalProportion).toFixed(2);
});

// 校验数据
const checkExtra = () => {
	let errArr: string[] = [];
	if (oilLists.value.length == 0) {
		errArr.push('请添加油相');
	}
	if (!Number(formData.NaOHPurity)) {
		errArr.push('请输入KOH纯度');
	}
	if (!Number(formData.water)) {
		errArr.push('请输入水相倍数');
	}
	// 校验添加物
	if (otherLists.value.length > 0) {
		otherLists.value.forEach((item) => {
			if (!item.name) {
				errArr.push('请输入添加物名称');
			}
			if (!Number(item.weight)) {
				errArr.push('请输入添加物重量');
			}
		});
	}
	if (activeTab.value == 2) {
		if (!Number(formData.totalOilWeight)) {
			errArr.push('请输入油相总重');
		}
		oilLists.value.forEach((item) => {
			if (!Number(item.proportion)) {
				errArr.push('请输入比例');
			}
		});
		// 比例总和为100%
		if (Number(restProportion.value) !== 0) {
			errArr.push('比例总和应为100%');
		}
	} else {
		oilLists.value.forEach((item) => {
			if (!Number(item.weight)) {
				errArr.push('请输入油品重量');
			}
		});
	}
	return errArr;
};

const handleCompute = () => {
	// 校验数据
	const errArr = checkExtra();
	if (errArr.length > 0) {
		Taro.showToast({
			title: errArr[0],
			icon: 'none',
		});
		return;
	}
	let tempOilList = [];
	let tempTotalOilWeight = 0;
	if (activeTab.value == 2) {
		tempOilList = oilLists.value.map((v) => {
			return {
				...v,
				weight: computedWeight(v),
			};
		});
	} else {
		tempTotalOilWeight = oilLists.value.reduce(
			(pre: BigNumber, cur: any) => pre.plus(cur.weight || 0),
			new BigNumber(0)
		);
		tempOilList = oilLists.value.map((v) => {
			return {
				...v,
				proportion: new BigNumber(v.weight)
					.dividedBy(tempTotalOilWeight)
					.multipliedBy(100)
					.toFixed(2),
			};
		});
	}
	// 计算碱的重量（每种油的重量*该油的皂化价*（1-减碱%）
	const NaOHWeight = tempOilList
		.reduce(
			(pre: BigNumber, cur: any) =>
				pre.plus(
					new BigNumber(cur.weight)
						.multipliedBy(cur.zhj)
						.multipliedBy(
							new BigNumber(1).minus(
								new BigNumber(
									formData.substractNaOH || 0
								).dividedBy(100)
							)
						)
				),
			new BigNumber(0)
		)
		.toFixed(2);
	// 超脂/添加物总重
	const otherWeight = otherLists.value
		.reduce(
			(pre: BigNumber, cur: any) => pre.plus(cur.weight || 0),
			new BigNumber(0)
		)
		.toFixed(2);
	// INS总值=油品占总油品的比例*该油的INS值，累加值
	const totalINS = tempOilList
		.reduce(
			(pre: BigNumber, cur: any) =>
				pre.plus(
					new BigNumber(cur.proportion || 0)
						.dividedBy(100)
						.multipliedBy(cur.ins || 0)
				),
			new BigNumber(0)
		)
		.toFixed(2);
	// 水相重量=水相倍数*碱的重量
	const waterWeight = new BigNumber(formData.water)
		.multipliedBy(NaOHWeight)
		.toFixed(2);
	// 入模总重=油品总重+其他物总重
	const totalWeight = new BigNumber(tempTotalOilWeight)
		.plus(otherWeight)
		.plus(waterWeight)
		.toFixed(2);

	const data = {
		...formData,
		oilLists: tempOilList,
		otherLists: otherLists.value,
		activeTab: activeTab.value,
		...(activeTab.value == 1 ? { totalOilWeight: tempTotalOilWeight } : {}),
		NaOHWeight,
		waterWeight,
		otherWeight,
		totalINS,
		totalWeight,
		type: 'liquid',
	};
	Taro.navigateTo({
		url: `/pages/computedResult/index?obj=${encodeURIComponent(
			JSON.stringify(data)
		)}`,
	});
};
const clearData = () => {
	oilLists.value = [];
	otherLists.value = [];
	// 重置formData
	Object.assign(formData, initialFormData);
};

const otherLists = ref([] as any);
const addOther = () => {
	otherLists.value.push({
		id: Date.now(),
		name: '',
		weight: '',
	});
};
const deleteOther = (index: number) => {
	otherLists.value.splice(index, 1);
};

const oilLists = ref([] as any);
const deleteOil = (index: number) => {
	oilLists.value.splice(index, 1);
};

// 导航回来时，刷新数据
useLoad(() => {
	eventCenter.on('addOil', (list) => {
		console.log(list, 'handleCustomEvent');
		const temp = list.map((item: any) => ({ ...item, weight: 0 }));
		// 如果有重复数据，不添加重复的数据，添加新的数据
		const newOilLists = temp.concat(oilLists.value);
		const oilMap = new Map();
		newOilLists.forEach((item) => {
			oilMap.set(item.name, item);
		});
		oilLists.value = Array.from(oilMap.values());
	});
});

useUnload(() => {
	eventCenter.off('addOil');
});

// 添加格式化数字的方法
const formatNumber = (obj: any, field: string) => {
	if (obj[field]) {
		const num = parseFloat(obj[field]);
		if (!isNaN(num)) {
			// 如果是整数，直接返回
			if (Number.isInteger(num)) {
				obj[field] = num.toString();
			} else {
				// 如果有小数，保留两位小数
				obj[field] = num.toFixed(2);
			}
		}
	}
};
</script>
